<template>
    <div class="f_div" v-loading="loading">
        <div class="t_div">
            基础资料 / 客户 /客户管理 / <a href="#">{{ name }}</a>
        </div>
        <el-container>
            <el-header class="header">
                <div class="h_div">
                    <div class="h_in_vid">基础信息</div>
                </div>
            </el-header>
            <el-main class="main">
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
                    status-icon>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="地址类型" prop="ar_type" required>
                                <el-select v-model="ruleForm.ar_type" placeholder="请选择" :teleported="false">
                                    <el-option v-for="item in options" :key="item.dict_code" :label="item.dict_label"
                                        :value="item.dict_code" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="客户" prop="ar_client" required>
                                <el-input v-model="ruleForm.ar_client" placeholder="客户名称/编码" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="联系人" prop="ar_contact" required>
                                <el-input v-model="ruleForm.ar_contact" placeholder="请输入内容" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="联系电话" prop="ar_phone" required>
                                <el-input v-model="ruleForm.ar_phone" placeholder="请输入内容" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="邮编" prop="ar_postcode">
                                <el-input v-model="ruleForm.ar_postcode" placeholder="请输入内容" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="区域" prop="ar_region" required>
                                <el-input v-model="ruleForm.ar_region" placeholder="请输入内容" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <el-form-item label="详细地址" prop="ar_adrs" required>
                                <el-input v-model="ruleForm.ar_adrs" placeholder="请输入内容" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="备注信息" prop="ar_remarks">
                                <el-input v-model="ruleForm.ar_remarks" placeholder="请输入内容" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="16">
                            <el-form-item>
                                <el-button type="primary" style="width: 80px" @click="onSubmit">保存</el-button>
                                <el-button style="width: 80px" @click="cancel">取消</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-main>
        </el-container>
    </div>
</template>

<script>
import { onMounted, reactive, ref, nextTick, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { getRandomString } from "@/randomString/random.js";
import axios from "axios";
import $http from '@/axios/base.js';

export default {
    name: "app",
    setup() {
        let ruleForm = reactive({
            ar_id: 0,
            ar_type: "",
            ar_client: "",
            ar_contact: "",
            ar_phone: "",
            ar_postcode: "",
            ar_region: "",
            ar_adrs: "",
            ar_remarks: "",
            create_by: sessionStorage.getItem("empname"),
            create_time: new Date().toISOString().slice(0, 10).toString(),
            is_del: 0,
            update_by: "",
            update_time: "",
        });

        let router = useRouter();
        let route = useRoute();

        let name = ref();

        let rulelist = ref([
            {
                url: "",
            },
        ]);

        let rulelist2 = ref([
            {
                url: "",
            },
        ]);

        let loading = ref(false);

        let options = ref([]);


        let ruleFormRef = ref(null);
        let upload = ref(null);
        const dialogImageUrl = ref("");
        const dialogVisible = ref(false);
        const disabled = ref(false);

        const rules = reactive({
            ar_contact: [
                {
                    required: true,
                    message: "联系人不能为空",
                    trigger: "blur",
                },
            ],
            ar_phone: [
                {
                    required: true,
                    message: "手机号码不能为空",
                    trigger: "blur",
                },
                {
                    pattern:
                        /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/,
                    message: "请输入正确的手机号码格式",
                    trigger: "blur",
                },
            ],
            ar_type: [
                { required: true, message: '请选择地址类型', trigger: 'change' }
            ],
            ar_client: [
                { required: true, message: '请输入客户名称/编码', trigger: 'blur' }
            ],
            ar_region: [
                { required: true, message: '请输入区域', trigger: 'blur' }
            ],
            ar_adrs: [
                { required: true, message: '请输入详细地址', trigger: 'blur' }
            ],

        });

        function handleRemove(file) {
            console.log(file);
            const index = rulelist.value.indexOf(file);
            if (index !== -1) {
                rulelist.value.splice(index, 1);
            }
            const index2 = rulelist2.value.indexOf(file);
            if (index2 !== -1) {
                rulelist2.value.splice(index2, 1);
            }
        }

        function handlePictureCardPreview(file) {
            dialogImageUrl.value = file.url;
            dialogVisible.value = true;
        }

        function handleDownload(file) {
            var now = new Date();

            // 获取年、月、日、时、分、秒
            var year = now.getFullYear();
            var month = now.getMonth() + 1; // 注意月份是从 0 开始的
            var day = now.getDate();
            var imageUrl = file.url;
            var link = document.createElement("a");
            link.href = imageUrl;
            link.download =
                "七尾-" + year + month + day + getRandomString(8) + ".jpg";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        function handleExceed(files) {
            // 当上传的文件数量超过限制时，清空已上传的文件列表，并上传最新的文件
            upload.value.clearFiles();
            const file = files[0]; // 获取最新的文件
            file.uid = Date.now(); // 为文件生成唯一的标识符
            upload.value.handleStart(file); // 开始上传最新的文件
            //upload.value.submit();
        }

        const handleUploadSuccess = (response, file, fileList) => {
            // 处理上传成功的逻辑，如显示成功消息或更新UI
            console.log("上传成功", response, file, fileList);
        };

        const handleUploadError = (error, file, fileList) => {
            // 处理上传失败的逻辑，如显示错误消息或更新UI
            console.error("上传失败", error, file, fileList);
        };

        function onSubmit() {

            ruleFormRef.value.validate((valid) => {
                if (valid) {
                    //这里可以执行提交表单的操作，比如发送请求到后端
                    console.log(ruleForm);
                    if (ruleForm.ar_id == 0) {
                        $http
                            .post(`http://localhost:5261/api/Address_ment/AddAddress`, ruleForm)
                            .then((res) => {
                                if (res) {
                                    ElMessage.success("添加成功！！！");
                                    setTimeout(() => {
                                        router.push("/Address");
                                    }, 500);
                                } else {
                                    ElMessage.error("添加失败！！！");
                                }
                            })
                            .catch((err) => console.log(err));
                    } else {
                        ruleForm.update_by = sessionStorage.getItem("empname");
                        ruleForm.update_time = new Date()
                            .toISOString()
                            .slice(0, 10)
                            .toString();
                        $http
                            .put("http://localhost:5261/api/Address_ment/UpdAddress", ruleForm)
                            .then((res) => {
                                ElMessage.success("修改成功！！！");
                                setTimeout(() => {
                                    router.push("/Address");
                                }, 500);
                            })
                            .catch((err) => console.log(err));
                    }
                } else {
                    //验证没有通过
                    ElMessage.warning("请填写完整数据！！！");
                }
            });
        }

        function show(id) {
            console.log(id);
            $http
                .get(`http://localhost:5261/api/Address_ment/GetAddress/${id}`).then((res) => {
                    ruleForm.ar_id = res.ar_id;
                    ruleForm.ar_type=res.ar_type;
                    ruleForm.ar_client = res.ar_client;
                    ruleForm.ar_contact = res.ar_contact;
                    ruleForm.ar_phone = res.ar_phone;
                    ruleForm.ar_postcode = res.ar_postcode;
                    ruleForm.ar_region = res.ar_region;
                    ruleForm.ar_adrs = res.ar_adrs;
                    ruleForm.ar_remarks = res.ar_remarks;
                    ruleForm.update_time = res.update_time;
                })
                .catch((err) => console.log(err));
        }

        function showGender(value) {
            axios
                .get("http://localhost:5261/api/Sys_Dict_data/Get_Dict_Types", {
                    params: {
                        Dict_name: value,
                    },
                })
                .then((res) => {
                    if (value == "地址类型") options.value = res.data;
                })
                .catch((err) => console.log(err));
        }



        function cancel() {
            router.push("/Address");
        }

        onMounted(() => {
            openFullScreen1();
            showGender("地址类型");
            name.value = route.query.name;
            var id = route.query.id;
            if (id != 0) {
                show(id);
            } else {
                rulelist.value = [];
                rulelist2.value = [];
            }
        });

        const openFullScreen1 = () => {
            loading.value = true;
            setTimeout(() => {
                loading.value = false;
            }, 500);
        };

        return {
            loading,
            name,
            route,
            options,
            dialogImageUrl,
            dialogVisible,
            ruleForm,
            rules,
            ruleFormRef,
            rulelist,
            rulelist2,
            disabled,
            router,
            openFullScreen1,
            handleRemove,
            handlePictureCardPreview,
            handleDownload,
            handleExceed,
            handleUploadSuccess,
            handleUploadError,
            onSubmit,
            show,
            cancel,
            upload,
            showGender
        };
    },
};
</script>

<style scoped>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 50px;
    background-color: #006eff;
}

.el-radio-group {
    margin-right: 12px;
}

.t_div {
    margin-bottom: 20px;
    text-align: left;
    font-size: 14px;
    color: #b3b4b6;
}

a {
    text-decoration: none;
}

.f_div {
    padding: 0px 50px;
}

.h_div {
    border-bottom: 1px solid #f2f2f2;
    height: 39px;
}

.h_in_vid {
    width: 100px;
    height: 20px;
    margin-top: 20px;
    border-left: 5px solid #006eff;
}

.header {
    background-color: #ffffff;
    border-radius: 10px 10px 0px 0px;
}

.main {
    background-color: #ffffff;
    border-radius: 0px 0px 10px 10px;
    height: 820px;
}

.form_content {
    margin-left: 50px;
}
</style>